package com.study.controller;

import com.study.cycle.TestService3;
import com.study.cycle.TestService4;
import com.study.dto.MyQuery;
import com.study.dto.MyUser;
import com.study.dto.User;
import com.study.dto.UserDto;
import com.study.ext.ApplyInterface;
import com.study.ext.StrategyEnum;
import com.study.service.UserService;
import com.study.service.impl.MyUserService;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * @Author tanglingyu
 * @Date: 2021/05/24/ 10:46
 * @Description
 */

@RestController
public class TestController2 {

  @Autowired
  private ApplyInterface applyInterface;

  @Autowired
  private UserService userService;

  @Resource
  private MyUserService myUserService;

  @Resource
  private TestService4 testService4;

  @Resource
  private TestService3 testService3;

  @PostMapping("/ss")
  public String test1() throws Exception {
    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
    File file = new File("C:\\Users\\Administrator\\Desktop\\88426758-北京银行股份有限公司.jpg");
    byte[] bytesArray = new byte[(int) file.length()];
    FileInputStream fis = new FileInputStream(file);
    fis.read(bytesArray);
    ByteArrayResource contentsAsResource = new ByteArrayResource(bytesArray) {
      @Override
      public String getFilename() {
        return "filename";
      }
    };
    paramMap.add("filename", contentsAsResource);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
    final User user = restTemplate
        .postForObject("http://localhost:8080/ss1", paramMap, User.class);
    if (Objects.nonNull(user) && "tang".equals(user.getName())) {
      System.out.println("success");
    }
    return "ss";
  }


  @PostMapping("/ss1")
  public User test2(HttpServletRequest request) throws Exception {
    MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
    Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
    fileMap.forEach((s, file) -> {
      file.getName();
      try {
        byte[] bytes = file.getBytes();
      } catch (IOException e) {
        e.printStackTrace();
      }
    });
    User user = new User();
    user.setName("tang");
    user.setId(1000);
    return user;
  }

  @PostMapping("/batchInsert")
  public void batchInsert() {
    List<UserDto> list = new ArrayList<>();
    UserDto user;
    int count = 0;
    int maxCount = 10_0001;
    int pageSize = 2_0000;
    for (int i = 0; i < maxCount; ++i) {
      user = new UserDto();
      user.setName("tang" + i);
      user.setLocation("wuhan");
      user.setTestName("lingyu" + i);
      list.add(user);
      if (!CollectionUtils.isEmpty(list) && list.size() == pageSize) {
        count += userService.batchInsert(list);
        list.clear();
      }
      //是否是最后一次
      if (count > 0 && maxCount - count < pageSize && !CollectionUtils.isEmpty(list)) {
        count += userService.batchInsert(list);
        list.clear();
      }
    }
  }

  @PostMapping("/testStrategy")
  public void testStrategy() {
    applyInterface.newStrategyInterface(StrategyEnum.StrategyEnum1).deal();
  }

  /**
   * String[]->String,String
   *
   * @param myUser
   * @return
   */
  @PostMapping("/typeHandler")
  public String typeHandler(@RequestBody MyUser myUser) {
    myUserService.addUser(myUser);
    return "success";
  }


  @GetMapping("/typeHandler2")
  public String typeHandler2() throws Exception {
    List<MyUser> allUser = myUserService.getAllUser();
    //返回集合的时候集合一定不为null但是size可能 =0
    System.out.println(allUser.size());
    return "success";
  }

  @GetMapping("/typeHandler3")
  public String typeHandler3() throws Exception {
    //返回单个对象,如果查询不到会是null此时一定要注意npe
    final MyUser one = myUserService.getOne(2L);
    //Optional.of()还是会抛npe自定义异常没用
    final List<String> list = Optional.of(one).orElseThrow(() -> new Exception("错误")).getHobbies();
    //Optional.ofNullable()在内容为null的时候会抛出自定义异常
    final List<String> list2 = Optional.ofNullable(one).orElseThrow(() -> new Exception("错误"))
        .getHobbies();
    return "success";
  }

  @GetMapping("/test/nested")
  public MyUser testMybatis() {
    MyQuery myQuery = new MyQuery();
    MyUser myUser = new MyUser();
    myUser.setName("tang");
    myQuery.setMyUser(myUser);
    return myUserService.selectNested(myQuery);
  }

  @PostConstruct
  public void init(){
    System.out.println("beanPostProcessor...");
  }
}

